import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import { connect } from 'react-redux'
import LoadMore from './loadMore'
import MapUl from './map'
import { NoMore } from './style'

// 初始化一个组件的 state
const initialState = {
  data: [],
  hasMore: false,
  isLoadingMore: false,
  page: 0
}
class SearchList extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
    this.state = initialState
  }
  render() {
    return (
      <div>
        {
          this.state.data.length
            ? <MapUl data={this.state.data} ShowListUl={this.props.ShowListUl} />
            : <div>{/* 加载中... */}</div>
        }
        {
          this.state.hasMore
            ? <LoadMore isLoadingMore={this.state.isLoadingMore} loadMoreFn={this.loadMoreData.bind(this)} />
            : <NoMore>没有更多数据</NoMore>
        }

      </div>
    )
  }
  componentDidMount() {
    // 获取首页数据
    this.loadFirstPageData()
  }
  // 获取首页数据
  loadFirstPageData() {

    const result = this.props.httpDatas()
    this.resultHandle(result)
  }
  // 加载更多数据
  loadMoreData() {
    // 记录状态
    this.setState({
      isLoadingMore: true
    })


    const result = this.props.httpDatas()
    this.resultHandle(result)

    // 更新状态
    this.setState({
      isLoadingMore: false
    })
  }
  // 处理数据
  resultHandle(result) {

    // 增加 page 计数
    const page = this.state.page
    this.setState({
      page: page + 1
    })

    result.then(res => {
      return res
    }).then(json => {

      const hasMore = this.state.data.length > 40 ? false : true
      const data = json.data

      this.setState({
        hasMore: hasMore,
        // 注意，这里讲最新获取的数据，拼接到原数据之后，使用 concat 函数
        data: this.state.data.concat(data)
      })
      console.log(1213, this.state)
    }).catch(ex => {

      console.error('搜索页获取数据报错, ', ex.message)

    })
  }
  // 处理重新搜索
  componentDidUpdate(prevProps, prevState) {
    const keyword = this.props.keyword
    const category = this.props.category

    // 搜索条件完全相等时，忽略。重要！！！
    if (keyword === prevProps.keyword && category === prevProps.category) {
      return
    }

    // 重置 state
    this.setState(initialState)

    // 重新加载数据
    this.loadFirstPageData()
  }
}

// -------------------redux react 绑定--------------------

function mapStateToProps(state) {
  return {
   
  }
}

function mapDispatchToProps(dispatch) {
  return {
  }
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(SearchList)